import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Skeleton, message } from 'antd';
import { formatMessage } from 'umi';
import { size } from 'lodash';
import { useRequest } from '@/hooks';
import { checkVerificationCode, resetForgetPassword } from '@/pages/EntryManage/services';
import { history } from 'umi'
import PopoverPasswordInput from '@/components/PopoverPasswordInput';

// 设置新密码
const SetNewPassword = ({ form, email, name, verificationKey, verificationValue, setIsLinkTimeout, redirectId }) => {
    const { getFieldDecorator } = form;
    const [disabled, setDisabled] = useState(true);

    // 校验验证码是否过期
    const { loading: checkCodeLoading } = useRequest(
        () =>
            checkVerificationCode({
                type: 10,
                organizeType: 1,
                loginName: email,
                key: verificationKey,
                value: verificationValue
            }),
        {
            onSuccess: res => {
                if (res?.code !== 10000) {
                    setIsLinkTimeout(true);
                }
            }
        }
    );

    // 修改密码
    const { loading: resetPwdLoading, run: runResetPwd } = useRequest(params => resetForgetPassword(params), {
        manual: true
    });

    // 按钮是否disabled状态
    useEffect(() => {
        const values = form.getFieldsValue();
        const arr = Object.values(values).filter(item => !item || item === '');
        let hasError = false;
        Object.keys(values).forEach(item => {
            if (size(form.getFieldError(item)) > 0) {
                hasError = true;
            }
        });
        setDisabled(hasError || size(arr) > 0);
    }, [form]);

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const payload = {
                    ...values,
                    verificationKey,
                    verificationValue,
                    loginName: email,
                    organizeType: 1
                };
                const { code, msg } = (await runResetPwd(payload)) || {};
                if (code === 10000) {
                    history.push({
                        pathname: '/external/interview/resetPassword',
                        query: { step: 4, name, id: redirectId }
                    });
                } else {
                    message.error(msg);
                }
            }
        });
    };

    return (
        <Skeleton loading={checkCodeLoading}>
            <Form hideRequiredMark>
                <Form.Item className="noErrorStyle" label={<span style={{ fontSize: 16 }}>密码</span>}>
                    {getFieldDecorator('newPassword', {
                        rules: [
                            {
                                validator(rule, value, callback) {
                                    const tempValue = value?.trim();
                                    if ((tempValue && tempValue.length < 8) || tempValue.length > 20) {
                                        callback(
                                            formatMessage({
                                                id: 'form.passwordRuleStep1.validate'
                                            })
                                        );
                                    } else if (!/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(tempValue)) {
                                        callback(
                                            formatMessage({
                                                id: 'form.passwordRuleStep2.validate'
                                            })
                                        );
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <PopoverPasswordInput
                            size="large"
                            onChange={e => {
                                // 关联校验
                                const pwdIsError = form.getFieldError('newPassword');
                                const tempvalue = form.getFieldValue('confirmNewPassword')?.trim();
                                if (size(pwdIsError) === 0 && tempvalue && tempvalue !== e.target.value?.trim()) {
                                    form.validateFields(['confirmNewPassword']);
                                }
                            }}
                            checkList={() => {
                                const value = form.getFieldValue('newPassword')?.trim();
                                const arr = [];
                                if (value) {
                                    if (value.length >= 8 && value.length <= 20) {
                                        arr.push(
                                            formatMessage({
                                                id: 'form.passwordRuleStep1.validate'
                                            })
                                        );
                                    }
                                    if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(value)) {
                                        arr.push(
                                            formatMessage({
                                                id: 'form.passwordRuleStep2.validate'
                                            })
                                        );
                                    }
                                }
                                return arr;
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label={<span style={{ fontSize: 16 }}>确认密码</span>}>
                    {getFieldDecorator('confirmNewPassword', {
                        rules: [
                            {
                                required: true,
                                message: '请输入'
                            },
                            {
                                validator(rule, value, callback) {
                                    if (value) {
                                        const tempValue = value?.trim();
                                        const password = form.getFieldValue('newPassword')?.trim();
                                        if (tempValue === password) {
                                            callback();
                                        } else {
                                            callback(formatMessage({ id: 'validation.password.twice' }));
                                        }
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<Input.Password placeholder="请输入" size="large" allowClear />)}
                </Form.Item>
                <Form.Item style={{ textAlign: 'center', paddingTop: 12 }}>
                    <Button
                        disabled={disabled}
                        loading={resetPwdLoading}
                        block
                        type="primary"
                        size="large"
                        onClick={handleSubmit}
                    >
                        完成
                    </Button>
                </Form.Item>
            </Form>
        </Skeleton>
    );
};

export default Form.create()(SetNewPassword);
